package com.cn.txx.web.socket;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import com.cn.txx.utils.Constants;


@Configuration
@EnableWebMvc
@EnableWebSocket
public class SocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
		
		private Logger logger = Logger.getLogger(this.getClass());

        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        	try {
        		 //前台 可以使用websocket环境
                registry.addHandler(myWebSocketHandler(),Constants.WEBSOCKET_URL).addInterceptors(new HandshakeInterceptor());


                //前台 不可以使用websocket环境，则使用sockjs进行模拟连接
                registry.addHandler(myWebSocketHandler(), Constants.WEBSOCKET_JSURL).addInterceptors(new HandshakeInterceptor())
                        .withSockJS();
                
                logger.info("websocket注册成功,URL为["+Constants.WEBSOCKET_URL+"],sockjs URl为["+Constants.WEBSOCKET_JSURL+"]");
			} catch (Exception e) {
				 logger.error("websocket注册失败",e);
			}
           
        }


        // websocket 处理类
        @Bean
        public WebSocketHandler myWebSocketHandler(){
            return new MyWebSocketHandler();
        }
}
